package com.artisan.domain.service;

import com.artisan.domain.dto.AccountDto;
import com.artisan.domain.dto.RegionDto;
import com.artisan.domain.entity.MRegion;
import com.artisan.domain.repositoryInterface.IRegionRepository;
import com.artisan.domain.serviceInterface.IRegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RegionService implements IRegionService {
  @Autowired private IRegionRepository jpaRegionRepository;

  @Override
  public List<RegionDto> findList() {
    List<MRegion> models = this.jpaRegionRepository.findAll();
    List<RegionDto> dtos = new ArrayList<>();
    models.forEach(
        model -> {
          RegionDto dto = new RegionDto();
          BeanUtils.copyProperties(model, dto);
          dtos.add(dto);
        });
    return dtos;
  }

    @Override
    public int add(RegionDto dto) {
        MRegion model = new MRegion();
        BeanUtils.copyProperties(dto, model);
        this.jpaRegionRepository.saveAndFlush(model);
        return model.getId();
    }

    @Override
    public RegionDto find(int id) {
        MRegion model = this.jpaRegionRepository.findById(id).get();
        RegionDto dto = new RegionDto();
        BeanUtils.copyProperties(model, dto);
        return dto;
    }

    @Override
    public boolean update(RegionDto dto) {
        MRegion model = this.jpaRegionRepository.findById(dto.getId()).get();
        model.setName(dto.getName());
        model.setParentId(dto.getParentId());

        this.jpaRegionRepository.saveAndFlush(model);
        return true;
    }

    @Override
    public boolean delete(int id) {
        this.jpaRegionRepository.deleteById(id);
        return true;
    }
}
